//
//  SKXFriendManager.m
//  NewChat
//
//  Created by songKX on 16/3/5.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "SKXFriendManager.h"

@interface SKXFriendManager()<NSURLSessionDataDelegate,NSURLSessionDelegate>



@property (nonatomic , assign)NSInteger duration;

@property (nonatomic , strong)NSString * recordPath;

@property (nonatomic , strong)NSString * chater;



@end

@implementation SKXFriendManager

static UIImageView *tempImgView = nil;

static SKXFriendManager *manager = nil;

static NSString *tempUrl = nil;

+(instancetype)sharaFriendManager{
        
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        
        manager = [[SKXFriendManager alloc] init];
        
        manager.friendAcceptArray = [[NSMutableArray alloc] init];
        manager.historyAcceptArray = [[NSMutableArray alloc] init];
        
    });
    
    return manager;
    
}

//添加好友
-(void)addFriendWithName:(NSString *)name{
    
    EMError *error = nil;
    
    NSString *currentUserName = [[EaseMob sharedInstance].chatManager loginInfo][@"username"];
    
    NSString *message = [NSString stringWithFormat:@"%@想添加你为好友",currentUserName];
    
    BOOL isSuccess = [[EaseMob sharedInstance].chatManager addBuddy:name message:message error:&error];
    if (isSuccess && !error) {
        NSLog(@"添加成功");
        
    }else{
        
        NSLog(@"添加好友失败");
    }
    
}

-(void)startRecordVoiceWithFileName:(NSString *)fileName{
    
    NSString *fileN = nil;
    
    if (fileName == nil) {
        
        int x = arc4random()%100000;
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        fileN = [NSString stringWithFormat:@"%d%d",(int)time,x];
        
        
    }else{
        
        fileN = fileName;
        
    }
    
    [[EMCDDeviceManager sharedInstance]asyncStartRecordingWithFileName:fileN completion:^(NSError *error) {
        
        if (!error) {
            
            NSLog(@"开始录音成功");
            
        }
        
        
    }];
    
}


-(void)stopRecordVoiceWithBlock:(VocieBlock)block{
    
    
    [[EMCDDeviceManager sharedInstance]asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
        
        if (!error) {
            NSLog(@"结束录音，录音成功");
            
            block(recordPath);
            
        }
        
    }];
    
    
}

-(void)cancelRecordVoice{
    
    NSLog(@"取消录音");
    
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
    
    
}

-(void)sendVoiceMessageto:(NSString *)chater With:(messageBlock)block{
    
    
    [[EMCDDeviceManager sharedInstance]asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
        
        if (!error) {
            NSLog(@"结束录音，录音成功");
            
            //发送语音给服务器
            
            
            //构造语音对象
            
            EMChatVoice *chatVoice = [[EMChatVoice alloc] initWithFile:recordPath displayName:@"语音"];
            
            chatVoice.duration = aDuration;
            
            //构造一个语音消息体
            
            EMVoiceMessageBody *voiceBudy = [[EMVoiceMessageBody alloc] initWithChatObject:chatVoice];
            
            voiceBudy.duration = aDuration;
            
            //构造消息对象
            
            EMMessage *temp = [[EMMessage alloc] initWithReceiver:chater bodies:@[voiceBudy]];
            
            [[EaseMob sharedInstance].chatManager asyncSendMessage:temp progress:nil prepare:^(EMMessage *message, EMError *error) {
                
                NSLog(@"语音准备发送");
                
            } onQueue:nil completion:^(EMMessage *message, EMError *error) {
                
                if (!error) {
                    
                    NSLog(@"语音发送成功");
                    
                }
                
            } onQueue:nil];
            
            block(temp);
            
        }
        
    }];
    
}


+(void)playVoiceWith:(EMMessage *)message WithMessageLabel:(UILabel *)label Bool:(BOOL)receiver
{
    
    //把以前的动画移除
    [tempImgView stopAnimating];
    [tempImgView removeFromSuperview];
    
    //1.播放语音
    //获取语音路径
    EMVoiceMessageBody *voiceBody = message.messageBodies[0];
    
    //本地语音文件
    NSString *path = voiceBody.localPath;
    
    //如果本地语音文件不存在，使用服务器语音
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        
        tempUrl = voiceBody.localPath;
        
        
        NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration delegate:[SKXFriendManager sharaFriendManager] delegateQueue:[NSOperationQueue mainQueue]];
        
        NSURLSessionDataTask *task3 = [session dataTaskWithURL:[NSURL URLWithString:voiceBody.remotePath]];
        
        
        [task3 resume];
        
    }else{
        
        
        [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:path completion:^(NSError *error) {
            NSLog(@"语音播放完毕 %@", error);
            
            //移除动画
            [tempImgView stopAnimating];
            [tempImgView removeFromSuperview];
        }];
        
    }
    NSLog(@"%@",voiceBody.localPath);
    
    
    
    
    //2.添加动画
    //2.1创建一个UIImageView  添加到label上
    UIImageView *imageV = [[UIImageView alloc] init];
    
    [label addSubview:imageV];
    
    //2.2添加动画的图片
    if (receiver) {
        //使用接收方的图片
        imageV.frame = CGRectMake(0, 0, 30, 30);
        imageV.animationImages = @[[UIImage imageNamed:@"chat_receiver_audio_playing000"] ,
                                   [UIImage imageNamed:@"chat_receiver_audio_playing001"] ,
                                   [UIImage imageNamed:@"chat_receiver_audio_playing002"] ,
                                   [UIImage imageNamed:@"chat_receiver_audio_playing003"]];
    }else{
        //使用发送方的图片
        imageV.frame = CGRectMake(label.bounds.size.width - 30, 0, 30, 30);
        imageV.animationImages = @[[UIImage imageNamed:@"chat_sender_audio_playing_000"] ,
                                   [UIImage imageNamed:@"chat_sender_audio_playing_001"] ,
                                   [UIImage imageNamed:@"chat_sender_audio_playing_002"] ,
                                   [UIImage imageNamed:@"chat_sender_audio_playing_003"]];
        
    }
    
    imageV.animationDuration = 1;
    
    [imageV startAnimating];
    tempImgView = imageV;
    
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    
    [data writeToFile:tempUrl atomically:YES];
    
    
    [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:tempUrl completion:^(NSError *error) {
        NSLog(@"语音播放完毕 %@", error);
        
        //移除动画
        [tempImgView stopAnimating];
        [tempImgView removeFromSuperview];
    }];
    
    
}


+(void)playVoiceWith:(NSString *)filePath WithButton:(UIButton *)button{
    
    
    UIImageView *imageV = [[UIImageView alloc] init];
    
    [button addSubview:imageV];
    
    imageV.frame = CGRectMake(0, 0, 30, 30);
    imageV.animationImages = @[[UIImage imageNamed:@"chat_receiver_audio_playing000"] ,
                               [UIImage imageNamed:@"chat_receiver_audio_playing001"] ,
                               [UIImage imageNamed:@"chat_receiver_audio_playing002"] ,
                               [UIImage imageNamed:@"chat_receiver_audio_playing003"]];
    
    imageV.animationDuration = 1;
    
    [imageV startAnimating];
    tempImgView = imageV;
    
//    NSURLSession *session = [NSURLSession sharedSession];
    
    
    //    NSURLSessionDataTask *task = []
    
    
    
    [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:filePath completion:^(NSError *error) {
        NSLog(@"语音播放完毕 %@", error);
        
        //移除动画
        [tempImgView stopAnimating];
        [tempImgView removeFromSuperview];
    }];
    
}
+(void)playVoiceWith:(NSString *)filePath WithLabel:(UIButton *)button{
    
    [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:filePath completion:^(NSError *error) {
        NSLog(@"语音播放完毕 %@", error);
    }];
}

+(void)checkNetWork:(void(^)(NSString *status))block{
    
    
    [GLobalRealReachability reachabilityWithBlock:^(ReachabilityStatus status) {
        switch (status)
        {
            case RealStatusNotReachable:
            {
                
                block(@"无网络连接");
                
                break;
            }
                
            case RealStatusViaWiFi:
            {
                
                block(@"正在使用WiFi");
                
                break;
            }
                
            case RealStatusViaWWAN:
            {
                
                block(@"正在使用流量");
                
                break;
            }
                
            default:
                break;
        }
    }];
    
}

+(void)phoneVibrate{
    
    //调用系统方法
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
    [[EMCDDeviceManager sharedInstance] playVibration];

    
    
}

+(void)phoneVoice{
    
    
    //调用系统方法
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];

    
    AudioServicesPlaySystemSound(1106);
    
}

+(void)stop{
    
    [[EMCDDeviceManager sharedInstance] stopPlaying];
    [tempImgView stopAnimating];
    
    [tempImgView removeFromSuperview];
    
}

+(NSString *)timeStr:(long long)timestamp{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    //1.获取当前的时间
    NSDate *currentDate = [NSDate date];
    
    //获取年，月，日
    NSDateComponents *currentComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
    
    
    //2.获取消息发送时间
    NSDate *messageDate = [NSDate dateWithTimeIntervalSince1970:timestamp/1000];
    
    //获取年，月，日
    NSDateComponents *messageComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:messageDate];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (currentComponents.year == messageComponents.year
        && currentComponents.month == messageComponents.month
        && currentComponents.day == messageComponents.day) {//今天
        dateFormatter.dateFormat = @"HH:mm";
    } else if ((currentComponents.year == messageComponents.year
                && currentComponents.month == messageComponents.month
                && currentComponents.day - 1 == messageComponents.day) ||
               
               //当昨天是上个月的最后一天
               (currentComponents.month - 1 == messageComponents.month && currentComponents.day == 1)){//昨天
        dateFormatter.dateFormat = @"昨天 HH:mm";
    }else{//昨天以前
        dateFormatter.dateFormat = @"yyy-MM-dd HH:mm";
    }
    
    return [dateFormatter stringFromDate:messageDate];
    
    
}


@end
